<template>
  <t-adaptive-page
      v-loading="state.loading"
      class="menu_mange"
      tableTitle="通电（进度）验收单列表"
      row-key="path"
      isCopy
      ref="tAdaptivePageRef"
      isExpansion
      :isTTableSelfFilling="false"
      :isShowPagination="false"
      columnSetting
      :table="state.table"
      :columns="state.table.columns"
      isShowWidthSize
      :opts="opts"
      :widthSize="4"
      @submit="conditionEnter"
      @radio-change="selecUpdateChange"
  >

    <template #CreateDate="{scope}">
      <div>{{ parseTime(scope.row.CreateDate) }}</div>
    </template>
    <template #CheckDate="{scope}">
      <div>{{ parseTime(scope.row.CheckDate) }}</div>
    </template>

    <template #toolbar>
      <div v-if="state.selectedRow">
        <el-button type="primary"  @click="handlEedit(state.selectedRow)"  v-if="['0'].includes(state.selectedRow.State) && checkPermission('修改', state.roleList)">编辑</el-button>
        <el-button type="primary"  @click="deleteHandles(state.selectedRow)" v-if="['0'].includes(state.selectedRow.State) && checkPermission('删除', state.roleList)">删除</el-button>
        <el-button type="primary"  @click="handlCheck(state.selectedRow,'2')" v-if="['0'].includes(state.selectedRow.State)  && checkPermission('审核', state.roleList)">审核</el-button>
        <el-button type="primary"  @click="handlCheck(state.selectedRow, '0')" v-if="['2'].includes(state.selectedRow.State)  && checkPermission('弃审', state.roleList)">弃审</el-button>
        <el-button   @click="handlCheck(state.selectedRow,'3')" type="primary"  v-if="state.selectedRow.State!=='3'  && checkPermission('关闭', state.roleList)" >关闭</el-button>

      </div>
      <div v-else style="color: #606266; font-size: 13px;">
        选择数据后显示操作按钮
      </div>
    </template>
    <template #State="{scope}">
      <el-tag type="info" v-if="scope.row.State=='0'">开立</el-tag>
      <el-tag type="success" v-if="scope.row.State=='2'">已审核</el-tag>
      <el-tag type="primary" v-if="scope.row.State=='1'">送审中</el-tag>
      <el-tag type="danger" v-if="scope.row.State=='3'">已关闭</el-tag>
    </template>

    <template #JobNum="{ scope }">
      <div>
        <el-link
            link
            @click="viewCheck(scope.row)"
            type="primary"
        >{{ scope.row.JobNum }}</el-link>
      </div>
    </template>

    <template #Ddate="{ scope }">
      <span> {{parseTime(scope.row.Ddate,'{y}-{m}-{d}') }}</span>
    </template>


    <template #footerBtn>
      <el-button type="danger" @click="addHandle()" v-if="checkPermission('新增', state.roleList)">新增</el-button>
      <!--      <el-button type="danger" @click="addHandle()" v-if="checkPermission('新增', state.roleList)">新增</el-button>-->
<!--      <el-button type="danger" @click="deleteHandles" :disabled="!state.ids.length" v-if="checkPermission('删除', state.roleList)">删除</el-button>-->
      <el-button type="primary" @click="tAdaptivePageRef.TQueryConditionPage.checkHandle()">查询</el-button>
      <el-button type="danger" @click="tAdaptivePageRef.TQueryConditionPage.resetHandle()">重置</el-button>
    </template>


  </t-adaptive-page>
  <!--  新增 / 修改-->
  <el-dialog :title="state.title" :style="{ width: '90%', maxWidth: '1200px' }" v-model="state.dialogSelectEnt" draggable :close-on-click-modal="false" @close="closeDialog">
    <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="right" label-width="160px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工作号" prop="JobNum">
            <JobNumberDropdown
                :isUseGlobalData="false"
                :disabled="state.formData.Id"
                v-model="state.formData.JobNum"
                @change="updateContarctInfo"
                :contract-list="state.contractList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同号" prop="ContractNum">
            <el-input v-model="state.formData.ContractNum" disabled placeholder="请输入合同号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目名称" prop="EntryName">
            <el-input v-model="state.formData.EntryName" disabled placeholder="请输入项目名称" clearable />
          </el-form-item>
        </el-col>


      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="需方单位" prop="Demand">
            <el-select
                v-model="state.formData.Demand"
                filterable
                remote
                disabled
                reserve-keyword
                placeholder="请选择需方单位"
                :remote-method="cnvbasdocMethod"
                :loading="state.loading"
                remote-show-suffixs
            >
              <el-option
                  v-for="(item,index) in cusoptions"
                  :key="index"
                  :label="item.ccusabbname"
                  :value="item.cCusCode">
                <span style="float: left">{{ item.ccusabbname }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">【{{item.cCusCode}}】</span>
              </el-option>
            </el-select>
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item label="需方现场代表" prop="PartyA">
            <el-input v-model="state.formData.PartyA"   placeholder="请输入需方现场代表" clearable  />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="供方单位" prop="SuppCode">
            <el-input v-model="state.formData.SuppCode" disabled  placeholder="请输入供方单位" clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供方现场代表" prop="PartyB">
            <el-input v-model="state.formData.PartyB"  placeholder="请输入供方现场代表" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="资料确认日期" prop="Ddate">
            <el-date-picker
                v-model="state.formData.Ddate"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                clearable
                :disabled-date="disabledDate"
                placeholder="选择日期"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="YSConclusion">
            <el-input v-model="state.formData.YSConclusion" type="textarea"  placeholder="请输入验收结论" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="6" v-if="files.length && state.checkDatas.length > 0" v-for="(item,index) in files" :key="index" style="margin-bottom: 15px;">
          <div style="border-radius: 4px;">
            <el-form-item :label="item.FileName+':'" >
              <upload :limit="1" v-model="item.FileAdd" @file-uploaded="(e) =>uploadSuccess(e,item.FileName)"></upload>
            </el-form-item>
          </div>
        </el-col>

      </el-row>
    </el-form>
    <t-layout-page-item>
      <t-table
          title="明细"
          ref="singleEdit"
          show-summary
          sortable
          :table="state.clumTable"
          :columns="state.clumTable.columns"
          :isShowPagination="false"
          :listTypeInfo="state.clumTable.listTypeInfo"
          :expand-row-keys="expandedRowKeys"
          @selection-change="checkChange"
          :row-key="row => row.ConSubId"
      >
        <template #toolbar>
          <div  style="color: red; font-size: 16px;font-weight: bold;">
            选择数据后显示上传文件
          </div>
        </template>

        <template #FileAdd="{ scope }">
          <el-popover :width="600">
            <template #reference>
              <el-link type="primary">
                {{(scope.row.TDYSJDFile?.length && getFileStatus(scope.row.TDYSJDFile) !== 'N') ? '查看文件【'+ scope.row.TDYSJDFile?.length +'】': '未上传'}}
              </el-link>
            </template>
            <template #default>
              <div
                  class="demo-rich-conent"
                  style="display: flex; gap: 16px; flex-direction: column"
              >
                <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
                  <li :key="index" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in scope.row.TDYSJDFile">
                    <el-link :href="`${file.FileAdd}`" :underline="false" target="_blank">
                      <span class="el-icon-document"> {{ file.FileName + '【' + (file.FileAdd ? '已上传' : '未上传') + '】'}} </span>
                      <span style="margin-left: 8px;color: red">{{parseTime(file.CreateDate)}}</span>
                    </el-link>
                  </li>
                </transition-group>
              </div>
            </template>
          </el-popover>
        </template>

        <template #Qty="{ scope }">
          <el-input
              v-model.number="scope.row.Qty"
              size="mini"
              :placeholder="'输入(0-' + scope.row.WTDYSQty + ')'"
              clearable
          />
        </template>
      </t-table>

    </t-layout-page-item>

    <template #footer>
      <div class="dialog-footer" style="display: flex; justify-content: flex-end; gap: 10px;">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>


  <!--  详情-->
  <el-dialog :title="state.detail.title" :style="{ width: '90%', maxWidth: '1200px' }" v-model="state.detail.dialogSelectEnt" draggable :close-on-click-modal="false" @close="closeDialog">
    <el-form ref="formRef" :model="state.detail.formData"  label-position="right" label-width="160px" :disabled="!state.isEdit">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作号" prop="JobNum">
            <JobNumberDropdown
                v-model="state.detail.formData.JobNum"
                @change="updateContarctInfo"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同号" prop="ContractNum">
            <el-input v-model="state.detail.formData.ContractNum" disabled placeholder="请输入合同号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目名称" prop="EntryName">
            <el-input v-model="state.detail.formData.EntryName" disabled placeholder="请输入项目名称" clearable />
          </el-form-item>
        </el-col>


      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="需方单位" prop="Demand">
            <el-select
                v-model="state.detail.formData.Demand"
                filterable
                remote
                disabled
                reserve-keyword
                placeholder="请选择需方单位"
                :remote-method="cnvbasdocMethod"
                :loading="state.loading"
                remote-show-suffixs
            >
              <el-option
                  v-for="(item,index) in cusoptions"
                  :key="index"
                  :label="item.ccusabbname"
                  :value="item.cCusCode">
                <span style="float: left">{{ item.ccusabbname }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">【{{item.cCusCode}}】</span>
              </el-option>
            </el-select>
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item label="需方现场代表" prop="PartyA">
            <el-input v-model="state.detail.formData.PartyA"   placeholder="请输入需方现场代表" clearable  />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="供方单位" prop="SuppCode">
            <el-input v-model="state.detail.formData.SuppCode" disabled  placeholder="请输入供方单位" clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供方现场代表" prop="PartyB">
            <el-input v-model="state.detail.formData.PartyB"  placeholder="请输入供方现场代表" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="资料确认日期" prop="Ddate">
            <el-date-picker
                v-model="state.detail.formData.Ddate"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                clearable
                placeholder="选择日期"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="YSConclusion">
            <el-input v-model="state.detail.formData.YSConclusion" type="textarea"  placeholder="请输入验收结论" clearable />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <t-layout-page-item>
      <el-table :data="state.detail.gridData" :default-sort="{prop: 'CinvCode', order: 'asc'}">
        <el-table-column label="设备编码" prop="CinvCode"></el-table-column>
        <el-table-column label="设备名称" prop="CinvName"></el-table-column>
        <el-table-column label="规格型号" prop="CinvAdd"></el-table-column>
        <el-table-column label="已发货数量" prop="YFHQty" width="110"></el-table-column>
        <el-table-column label="已通电数量" prop="YTDYSQty" width="110"></el-table-column>
        <el-table-column label="本次验收数量" prop="Qty"></el-table-column>
        <el-table-column label="客户产品名称" prop="CustCinvName"></el-table-column>
        <el-table-column label="客户产品规格" prop="CustCinvAdd"></el-table-column>
        <el-table-column label="单位" prop="Unit"></el-table-column>
        <el-table-column label="文件" prop="TDYSJDFile">
          <template #default="{ row }">
            <el-popover :width="600">
              <template #reference>
                <el-link type="primary">
                  {{(row.TDYSJDFile?.length && getFileStatus(row.TDYSJDFile) !== 'N') ? '查看文件【'+ row.TDYSJDFile?.length +'】': '未上传'}}
                </el-link>
              </template>
              <template #default>
                <div
                    class="demo-rich-conent"
                    style="display: flex; gap: 16px; flex-direction: column"
                >
                  <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
                    <li :key="index" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in row.TDYSJDFile">
                      <el-link :href="`${file.FileAdd}`" :underline="false" target="_blank">
                        <span class="el-icon-document"> {{ file.FileName + '【' + (file.FileAdd ? '已上传' : '未上传') + '】'}} </span>
                        <span style="margin-left: 8px;color: red">{{parseTime(file.CreateDate)}}</span>
                      </el-link>
                    </li>
                  </transition-group>
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>

      </el-table>
    </t-layout-page-item>

    <template #footer>
      <div class="dialog-footer" style="display: flex; justify-content: flex-end; gap: 10px;">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>


</template>

<script setup lang="tsx">
import {computed, onMounted, reactive, ref, toRefs, unref, watch} from "vue"
import {selcetDataList,saveTDYS,getOneTDYS,delTDYS,getOneSKJH,GetOnHT2,GetOneHTTDys} from "@/api/delivery_accept"
import {getContractList,ApproveDocument,userRole,getContractTDYSList} from "@/api/base"
import {parseTime,checkPermission,disabledDate} from "@/utils/util";
import {cubasdocStore} from "@/stores/modules/cubasdoc";
import {ElMessage} from "element-plus";
import JobNumberDropdown from "@/components/JobNumberDropdown/index.vue"



const tAdaptivePageRef: any = ref(null)


const cubasdoc = cubasdocStore()
const handlEedit = async (row: any)  => {
  await findContractList()

  let {Data} = await getOneTDYS({id:row.Id})
  state.formData = Data.Main
  state.title = "编辑通电（进度）验收单"
  //过滤合同
  let contractInfo = cubasdoc.contractList.find((item: any) => item.ContractNum == row.ContractNum)
  if (contractInfo){
    await findContractInfo(contractInfo.Id)
    state.clumTable.data = Data.SubList
    state.defaultSelectVal = Data.SubList.map((item: any) => item.ConSubId)
  }
  state.dialogSelectEnt = true

}

const handleDelete = (row: any) => {
  state.clumTable.data.splice(state.clumTable.data.indexOf(row), 1)
}
const handleUpload = (row: any) => {
  state.clumTable.data.splice(state.clumTable.data.indexOf(row), 1)
}

const uploadSuccess = (fileurl, fileName) => {

  // 先更新 checkDatas
  state.checkDatas.forEach(item => {
    if (Array.isArray(item.TDYSJDFile)) {
      const matchedFile = item.TDYSJDFile.find(file => file.FileName === fileName);
      if (matchedFile) {
        matchedFile.FileAdd = fileurl;
      }
    }
  });
}



const expandedRowKeys = ref([])
const expandChange = async (val: any, expandedRows: any) => {
  // 该处是用于判断是展开还是收起行，只有展开的时候做请求
  if (expandedRows.length > 0) {
    // 控制展开行
    expandedRowKeys.value = expandedRows.map(val => val.Id);
  }
}

const viewCheck = async (row: any)  =>{

  await findContractList()

  let {Data} = await getOneTDYS({id:row.Id})
  state.detail.formData = Data.Main
  state.detail.gridData = Data.SubList
  state.detail.title = "通电（进度）验收单详情"

  state.detail.dialogSelectEnt = true
  state.isEdit = false
}

const handleInput = async(val, row)=> {
  // 过滤非数字字符
  const cleanVal = String(val).replace(/\D/g, '');

  // 转换为数字 (空字符串转为0)
  const numVal = cleanVal === '' ? 0 : parseInt(cleanVal, 10);

  // 获取动态最大值
  const max = row.WTDYSQty || 0;

  // 范围限制
  if (numVal > max) {
    row.Qty = max;
  } else if (numVal < 0) {
    row.Qty = 0;
  } else {
    row.Qty = isNaN(numVal) ? 0 : numVal;
  }
}

const handlCheck = async (row: any,status: any)  => {
  //调用查询合同详细信息
  const ids = [row.Id];
  let data={
    "Ids": ids,  //单据id
    "Type":"TDYS",  //类型 HTLR 合同录入 TDYS 通电验收  FHYS 发货验收  JSD 结算单  SKJH 收款计划 SKD 收款单 YKP 预收款发票
    "State":status,
  }
  await ApproveDocument(data);
  ElMessage.success("审核成功")
  await getData()
}

//表格配置
const state: any = reactive({
  roleList: [],
  contractList: [],
  queryData: {
    JobNum: null, // 登录名
    ContractNum: null, // 用户状态
    SuppCode: null,
    Demand: null,
    CreateFrom: null,
    CreateTo: null,
    CreateBy: null
  },
  table: {
    border: true,
    // 接口返回数据
    data: [],
    firstColumn: { type: "radio", fixed: true },
    // 表头数据
    columns: [
      { prop: "JobNum", label: "工作号", minWidth: 120,fixed: 'left',slotName: 'JobNum' },
      { prop: "cCode", label: "通电验收单号", minWidth: 130,fixed: 'left' },
      { prop: "EntryName", label: "项目名称", minWidth: 150 },
      { prop: "ContractNum", label: "合同号",minWidth: 150},
      { prop: "SuppCode", label: "供方单位", minWidth: 120 },
      { prop: "State", label: "状态", minWidth: 120 ,slotName: "State"},
      // { prop: "PartyA", label: "甲方现场负责人", minWidth: 160 },
      { prop: "Demand", label: "需方单位", minWidth: 120 },
      // { prop: "PartyB", label: "乙方现场负责人", minWidth: 160},
      { prop: "Ddate", label: "资料确认时间", minWidth: 100,slotName: 'Ddate' },
      { prop: "CreateDate", label: "建单日期", minWidth: 160,slotName: "CreateDate"},
      { prop: "CreateBy", label: "建单人", minWidth: 120 },
      { prop: "CheckDate", label: "审核日期", minWidth: 160,slotName: "CheckDate"},
      { prop: "ApproveBy", label: "审核人", minWidth: 120}
    ],
  },
  loading:false,
  title: "新增通电（进度）验收单",
  dialogSelectEnt:false,
  formData: {
    JobNum: null, // 工作号
    ContractNum: null, // 合同号
    SuppCode: null,
    Demand: null,
    CreateFrom: null,
    CreateTo: null,
    CreateBy: null,
    PartyA:null,
    PartyB:null,
    EntryName:null,
    YSConclusion:null,
  },
  coseData:[],
  checkDatas:[],

  clumTable: {
    border: true,
    firstColumn: { type: "selection", fixed: true },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: "CinvCode",
        sortable: true,
        label: "设备编码",
        minWidth: 110
      },
      {
        prop: "CinvName",
        label: "设备名称",
        sortable: true,
        minWidth: 110
      },
      {
        prop: "CinvAdd",
        label: "规格型号",
        minWidth: 110
      },
      {
        prop: "YFHQty",
        label: "已发货数量",
        minWidth: 110
      },
      {
        prop: "YTDYSQty",
        label: "已通电数量",
        minWidth: 110
      },
      {
        prop: "Qty",
        label: "本次验收数量",
        sortable: true,
        slotName: "Qty",
        minWidth: 110
      },
      {
        prop: "FileAdd",
        label: "查看文件",
        slotName: "FileAdd",
        minWidth: 110
      },
      {
        prop: "CustCinvName",
        label: "客户产品名称",
        canEdit: true,
        minWidth: 120,
        configEdit: {
          label: "客户产品名称",
          type: "input",
          editComponent: "el-input"
        }
      },
      {
        prop: "CustCinvAdd",
        label: "客户产品规格",
        minWidth: 120,
        canEdit: true,
        configEdit: {
          label: "客户产品规格",
          type: "input",
          editComponent: "el-input"
        }
      },

      {
        prop: "Unit",
        label: "单位",
      },
    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: "上层",
          key: "1"
        },
        {
          label: "中层",
          key: "2"
        },
        {
          label: "下层",
          key: "3"
        }
      ]
    },
    operator: [
      {
        text: "删除",
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 100,
      label: "操作"
    }
  },
  editTable: {
    border: true,
    firstColumn: { type: "selection" },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: "CinvCode",
        label: "设备编码",
      },
      {
        prop: "CinvName",
        label: "设备名称",
      },
      {
        prop: "CinvAdd",
        label: "规格型号",

      },
      {
        prop: "Quantity",
        label: "数量",
      },
      {
        prop: "WTDYSQty",
        label: "未验收数量",
      },
      {
        prop: "Unit",
        label: "单位",

      },

    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: "上层",
          key: "1"
        },
        {
          label: "中层",
          key: "2"
        },
        {
          label: "下层",
          key: "3"
        }
      ]
    },
    operator: [
      {
        text: "删除",
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 200,
      label: "操作"
    }
  },

  rules:{
    ContractNum: [
      { required: false, message: '请选择合同号', trigger: 'change' },
    ],
    EntryName: [
      { required: true, message: '请输入项目名称', trigger: 'change' },
    ],
    SuppCode: [
      { required: true, message: '请选择供方单位', trigger: 'change' },
    ],
    Demand: [
      { required: true, message: '请选择需方单位', trigger: 'change' },
    ],
    PartyA: [
      { required: true, message: '请输入甲方现场负责人', trigger: 'blur' },
    ],
    JobNum: [
      { required: true, message: '请输入工作号', trigger: 'blur' },
    ],
    Ddate: [
      { required: true, message: '请选择资料确认时间', trigger: 'change' },
    ],
  },
  defaultSelectVal:[],
  ids:[],
  selectedRow:null,
  isEdit:false,
  detail:{
    dialogSelectEnt:false,
    title:"详情",
    formData: {},
  }

})


//表单配置
const opts = ref({
  JobNum: {
    label: "工作号",
    comp: "el-input",
    bind: {
      size: 'small',
    },
  },
  ContractNum: {
    label: "合同号",
    comp: "el-input",
    bind: {
      size: 'small',
    },
  },
  SuppCode: {
    label: "供方单位",
    placeholder: "请选择供方单位",
    comp: "t-select",
    isSelfCom: true,
    bind: {
      valueCustom: "cCusCode",
      labelCustom: "ccusname",
      optionSource: cubasdoc.data,
      size: 'small',
    },
  },
  Demand: {
    label: "需方单位",
    placeholder: "请选择需方单位",
    comp: "t-select",
    isSelfCom: true,
    bind: {
      size: 'small',
      valueCustom: "cCusCode",
      labelCustom: "ccusname",
      optionSource: cubasdoc.data
    },
  },
  CreateBy: {
    label: "建档人",
    comp: "el-input",
    bind: {
      size: 'small',
    },
  },

  CreateFrom: {
    label: "制单日期",
    comp: "t-date-picker",
    span: 1,
    bind: {
      size: 'small',
      type: "daterange"
    }
  }
})

//选择项
const cusoptions = ref(cubasdoc.data)


// 最终参数获取
const getQueryData = computed(() => {
  const { JobNum, ContractNum, CreateFrom, SuppCode, Demand, CreateBy } = toRefs(
      state.queryData
  )
  return {
    JobNum: JobNum.value,
    ContractNum: ContractNum.value,
    SuppCode: SuppCode.value,
    Demand: Demand.value,
    CreateBy: CreateBy.value,
    CreateFrom: CreateFrom.value && CreateFrom.value[0] ? CreateFrom.value[0] : null,
    CreateTo: CreateFrom.value && CreateFrom.value[1] ? CreateFrom.value[1] : null,
  }
})

// 点击查询按钮
const conditionEnter = (data: any) => {

  state.queryData = data

  getData()
}

//页面加载查询后端数据
onMounted(() => {
  getData()
  initRoleList()
})

async function findContractList() {
  let queryData = {
    "ContractType": null,
    "CustCode": null,
    "CustName": null,
    "ContractNum": null,
    "CreateFrom": null,
    "CreateTo": null,

    "Type":null,
    "IsMoudels":false,
    "State":'2',
    "CreateBy":null,
  }
  //获取合同信息
  let contractData = await getContractTDYSList(queryData)
  state.contractList = contractData.Data
}

// 获取数据
const getData = async () => {
  state.loading = true
  let data=await selcetDataList(getQueryData.value);

  if (data.Code==='OK'){
    state.table.data = data.Data
  }
  state.loading = false
}

//过滤单位
const cnvbasdocMethod = (query) => {

  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter((its) => {
        return (its.cCusCode.toLowerCase().includes(query.toLowerCase()) || its.ccusabbname.toLowerCase().includes(query.toLowerCase()))
      })
    }, 200)
  } else {
    cusoptions.value = cubasdoc.data
  }

}

function updateContarctInfo (e) {
  //查询过滤合同信息
  if (e){
    //赋值项目名称
    state.formData.EntryName = e?.ProjectName;
    state.formData.ContractNum = e?.ContractNum;
    state.formData.Demand = e?.CustCode;
    //调用查询合同详细信息
    findContractInfo(e.Id)
  }
  else {
    state.clumTable.data = []
  }
}

const  files= ref([])
//查询合同详细信息
async function findContractInfo (id) {
  let {Data}=await GetOneHTTDys({id: id})

  if (Data.Main?.TDYSJDFile){
    files.value = Data.Main?.TDYSJDFile.split(",").map(item=>{
      return {
        FileName: item,
        FileAdd: '',
      }
    })
  }
  if (Data?.SubList2){
    //赋值合同明细
    state.clumTable.data = Data.SubList2.map(item=>{
      return {
        ...item,
        JDFile: files.value,
        Qty:item.WTDYSQty,
        ConSubId: item.Id,
        Id:null
      }
    })

  }


}


//打开新增窗口
function addHandle() {
  reset()
  findContractList()
  state.dialogSelectEnt = true
}
const singleEdit: any = ref(null)
const selectTable = ref()

//关闭弹窗
function closeDialog() {
  reset()
  state.dialogSelectEnt = false
  state.detail.dialogSelectEnt = false
}

// 添加数据条数
const num = ref(1)

// 添加数据
const add = () => {
  if (num.value > 0) {
    for (let i = 0; i < num.value; i++) {
      state.editTable.data.push({})
    }
  }
}
// 重置表单
const reset = () => {
  state.formData = {
    SuppCode: "贵阳永青智控科技股份有限公司",
  }
  state.clumTable.data=[]
  selectTable.value?.clear()
  state.coseData= []
  state.defaultSelectVal=[]
  state.editTable.data=[]
  files.value=[]


  // singleEdit.value?.resetFields()
}

//下拉表格选择数据
const selectionChange = (e) => {
  state.coseData = e

}

//明细表格选择数据
const checkChange = (e) => {
  state.checkDatas = e

}

//下拉表格选择数据
const selecUpdateChange = (e) => {
  state.selectedRow = e
}


//校验表单需要定义ref
let formRef =ref({})
// 提交表单
function submitForm() {
  //校验提交表单
  formRef.value.validate(async (vaild) => {
    if (vaild){
      if (state.clumTable.data.length<=0){
        ElNotification.error({
          title: '提示',
          message: '请选择标的',
          offset: 200,
        })
        return
      }
      let data={
        Main: {
          ...state.formData,
          State: '0',
        },
        SubList:state.clumTable.data
      }

      let res= await saveTDYS(data)
      if (res.Code==='OK'){
        ElNotification.success({
          title: '提示',
          message: '保存成功',
          offset: 200,
        })
        closeDialog()
        await getData()

      }else {
        ElNotification.error({
          title: '提示',
          message:res.Result,
          offset: 200,
        })
      }

    }
  })


}


//删除表单
function deleteHandles(row) {

  const ids = row.Id ? [row.Id] : state.ids;


  ElMessageBox.confirm(
      '请仔细核对数据，删除后无法恢复！',
      '审核提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        delTDYS({Ids:ids})
        ElNotification.success({
          title: '提示',
          message:'删除成功',
          offset: 200,
        })
        setTimeout(() => {
          getData()
        },300)

      })
      .catch(() => {

      })


}

// 获取文件名称
function getFileStatus(files) {
  // 判断list中FileAdd是否都有值，全部有值返回完整，部分返回部分上传
  if (!Array.isArray(files) || files.length === 0) {
    return '无文件';
  }

  const allHaveValues = files.every(file => file.FileAdd !== undefined && file.FileAdd !== null && file.FileAdd !== '');
  const someHaveValues = files.some(file => file.FileAdd !== undefined && file.FileAdd !== null && file.FileAdd !== '');

  if (allHaveValues) {
    return 'Y';
  } else if (someHaveValues) {
    return 'B';
  } else {
    return 'N';
  }
}


const initRoleList = async () => {
  let res = await userRole({ VT_ID: '通电验收单' })
  state.roleList = res.items
}
</script>
